This article will discuss states in React. A component's properties cannot be altered. This is done for good reason because changing the properties would result in unclear data states, issues with the data structure, etc. However, a component may need to be able to update its state at times. For instance, changing a stopwatch's timer or setting an active flag. React gives us the option to hold state in our components to help us with this.
State in a component should only be accessible by the component and any children it uses, and it should be totally internal to the component and its children. The state can be retrieved via this in a manner similar to how we access props in a component. The component will refresh whenever the state changes (through the this.setState() function). Without state, we might set a timer and redraw the entire React component; however, other components on the page might not require a rerender, which would make integration into a more complex application difficult and slow.
Let's build a clock component. Try to recall how to make a component for two minutes. The initialization of the clock component would look like this.
First, we'll write a function that returns a javascript object with the values for the hours, minutes, seconds, and ampm. The code would be as follows.
By setting this.state to a value, we build the constructor's initial state.
To render this state, we will develop a render function
We'll utilize a special function named setState() to update the state, which will cause the component to refresh itself.We'll also employ a lifecycle hook, which will be discussed in the article after this one.
We'll develop lifecycle hooks, proptypes and styles in the next article. The complete code is available on my github.
« Read Previous Article in this Series Read Next Article in this Series »